#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "file_path.h"

#include "actions.h"

char *AT_NAMES[NUM_AT]={
    "No operation",
    "Synchronise",
    "Delete"
};

int A_init_v(sA *action, eAT type, va_list ap) {
    if(!action) return 1;

    action->type=type;

    switch(action->type) {
    case AT_SYNC:
        action->sync.file=strdup(va_arg(ap, char *));
        if(!action->sync.file) {
            A_deinit(action);
            return 1;
        }
        action->sync.dir=va_arg(ap, unsigned int);
        break;
    case AT_DEL:
        action->del.file=strdup(va_arg(ap, char *));
        if(!action->del.file) {
            A_deinit(action);
            return 1;
        }
        break;
    default:
        break;
    }

    return 0;
}

int A_handle_sync(sAT_sync *data, sSynq *synq);
int A_handle_del(sAT_del *data, sSynq *synq);

int A_run_simu(sA *action, sSynq *synq) {
    if(!action || !synq_is_usable(synq)) return 1;

    switch(action->type) {
    case AT_SYNC:
        return A_handle_sync(&action->sync, synq);
    case AT_DEL:
        return A_handle_del(&action->del, synq);
    default:
        return 0;
    }
}

int A_handle_sync(sAT_sync *data, sSynq *synq) {
    sST *file=FP_to_ST(synq->tree, data->file);   // get the file in the tree given the path
    if(!file) return 1;

    unsigned int i;
    for(i=0; i<synq->dirs.numdirs; i++) {
        if(i==data->dir) continue;

        memcpy(&file->files[i], &file->files[data->dir], sizeof(sFS));
    }

    return 0;
}

int A_handle_del(sAT_del *data, sSynq *synq) {
    sST *file=FP_to_ST(synq->tree, data->file);   // get the file in the tree given the path
    if(!file) return 1;

    ST_remove_data(&synq->tree, file);

    return 0;
}

void A_deinit(sA *action) {
    if(!action) return;

    switch(action->type) {
    case AT_SYNC:
        if(action->sync.file) free(action->sync.file);
        break;
    case AT_DEL:
        if(action->del.file) free(action->del.file);
        break;
    default:
        break;
    }

    bzero(action, sizeof(sA));
}

// ----

void A_print(sA *action) {
    if(!action) return;

    if(action->type>=0 && action->type<NUM_AT)
        printf("%s : ", AT_NAMES[action->type]);
    else
        printf("Unknown(%d) : ", action->type);

    switch(action->type) {
    case AT_SYNC:
        printf("%s, %d", action->sync.file, action->sync.dir);
        break;
    case AT_DEL:
        printf("%s", action->del.file);
        break;
    default:
        break;
    }
}

